import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './types'
import { bindUser, login, unBindUserInfo } from "../api/login";
import { getHasDoIndex, getTaskList } from "../api/task";

Vue.use(Vuex)

let lifeData = {};

try {
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
} catch (e) {

}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = [];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync('lifeData', tmp);
	}
}
const store = new Vuex.Store({
	state: {
		vuex_tabbar: [
			{
				"pagePath": "/pages/index/index",
				"iconPath": "/static/images/home.png",
				"selectedIconPath": "/static/images/home-select.png",
				"text": "首页"
			},
			{
				"pagePath": "/pages/flow/flow",
				"iconPath": "/static/images/dcfw.png",
				"selectedIconPath": "/static/images/dcfw-select.png",
				"text": "产地服务"
			},
			{
				"pagePath": "/pages/mine/mine",
				"iconPath": "/static/images/mine.png",
				"selectedIconPath": "/static/images/mine-select.png",
				"text": "我的"
			}
		],
		sid: '',
		userInfo: '',
		bindid: '',
		bindUser: '',
		indexData: {
			count: 0,
			taskList: [],
			more: true
		},
		hasDoInData: {
			count: 0,
			taskList: [],
			more: true
		},
		public: {
			taskData: {}
		},
		appointData:{
			count: 0,
			taskList: [],
			more: true
		}
	},
	mutations: {
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (len >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		},
		[types.LOGOUT](state) {
			state.bindid = ''
			state.bindUser = false
			state.userInfo = ''
			state.sid = ''
		},
		[types.LOGIN](state, payload) {
			state.bindid = payload.bindid
			state.bindUser = payload.bindUser
			state.userInfo = payload.userInfo
			state.sid = payload.sid
		},
		[types.TASK_LIST](state, payload) {
			let taskList = state.indexData.taskList;
			if (payload.loadMore) {
				taskList = taskList.concat(payload.taskList)
			} else {
				taskList = payload.taskList
			}
			if(payload.taskList){
				state.indexData = {
					taskList: taskList,
					more: payload.total > taskList.length,
					count: payload.total
				}
			}
			
		},
		[types.APPOINT_TASK_LIST](state, payload) {
			let taskList = state.appointData.taskList;
			if (payload.loadMore) {
				taskList = taskList.concat(payload.taskList)
			} else {
				taskList = payload.taskList
			}

			state.appointData = {
				taskList: taskList,
				more: payload.total > taskList.length,
				count: payload.total
			}
		},
		[types.DO_IN_TASK_LIST](state, payload) {
			let taskList = state.hasDoInData.taskList;
			if (payload.loadMore) {
				taskList = taskList.concat(payload.taskList)
			} else {
				taskList = payload.taskList
			}

			state.hasDoInData = {
				taskList: taskList,
				more: payload.total > taskList.length,
				count: payload.total
			}
		},
		[types.TASK_DATA](state, payload) {
			state.public.taskData = payload
		}
	},
	getters: {
		taskData: (state) => state.public.taskData,
		userInfo: (state) => state.userInfo
	},
	actions: {
		async logout({ commit }) {
			wx.showLoading({
				title: '解绑中',
				mask: true
			})
			const { data, code } = await unBindUserInfo()
			if (code === 0) {
				commit(types.LOGOUT)
				this.dispatch('login')
			} else {
				wx.showModal({
					title: '提示',
					content: data.msg,
					showCancel: false,
				})
			}

		},
		async login({ commit }) {
			uni.showLoading({
				title: '自动登录',
				mask: true
			})

			const { data, code } = await login()

			uni.hideLoading()
			if (code === 0) {
				let payload = {
					bindid: data.bindid,
					bindUser: data.bindUser
				}
				if (data.bindUser) {
					let session = JSON.parse(data.sessionId);
					if (session.status === 1) {
						payload.sid = session.sessionId
						payload.userInfo = session
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						uni.showModal({
							title: '提示',
							content: session.msg,
							showCancel: false
						})
					}
					commit(types.LOGIN, payload)
				} else {
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
					if (page.route !== 'pages/login/login'){
						wx.redirectTo({
							url: '/pages/login/login',
						})
					}

				}
				commit(types.LOGIN, payload)
			} else {
				uni.showModal({
					title: '提示',
					content: '服务器繁忙',
				})
			}
		},
		async bindUser({ commit }, payload) {
			const { code, msg, data } = await bindUser({
				bindid: payload.bindid,
				userId: payload.userName,
				pwd: payload.password
			})
			if (code === 0) {
				var session = JSON.parse(data.sessionId);
				if (session.status === 1) {
					//跳转到列表
					const loginPayload = {
						bindUser: true,
						sid: session.sessionId,
						userInfo: session
					}
					commit(types.LOGIN, loginPayload)
					wx.switchTab({
						url: '/pages/index/index',
					})
					this.dispatch('getTaskList',{
						page:1
					})
				} else {
					wx.showModal({
						title: '提示',
						content: session.msg,
						showCancel: false,
					})
				}
			} else {
				uni.showToast({ title: msg, icon: 'none' })
			}
		},
		async getTaskList({ commit }, payload) {
			if (payload.loadMore) {
				if (!this.state.indexData.more) {
					return
				}
			}
			uni.showLoading({
				title: '在在加载',
				mask: true
			})
			const { data } = await getTaskList({
				page: payload.page,
			})
			commit(types.TASK_LIST, {
				...data,
				loadMore: payload.loadMore
			})
			uni.hideLoading()
		},
		async getAppointTaskList({ commit }, payload) {
			if (payload.loadMore) {
				if (!this.state.appointData.more) {
					return
				}
			}
			uni.showLoading({
				title: '在在加载',
				mask: true
			})
			const { data } = await getTaskList({
				page: payload.page,
				query: payload.query,
				wfid: payload.wfid
			})
			commit(types.APPOINT_TASK_LIST, {
				...data,
				loadMore: payload.loadMore
			})
			uni.hideLoading()
		},
		async getHasDoIndex({ commit }, payload) {
			if (payload.loadMore) {
				if (!this.state.hasDoInData.more) {
					return
				}
			}
			uni.showLoading({
				title: '在在加载',
				mask: true
			})
			const { data } = await getHasDoIndex({
				page: payload.page,
				query:payload.query
			})
			commit(types.DO_IN_TASK_LIST, {
				...data,
				loadMore: payload.loadMore
			})
			uni.hideLoading()
		},
		setTaskData({ commit }, taskData) {
			commit(types.TASK_DATA, taskData)
		},
	}
})

export default store
